﻿using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System;
using System.IO;

namespace Dora.Orm.Migration
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("确认要更新数据库吗？ y/n.");

            var ok = Console.ReadLine();

            if (ok.ToString().ToLower() == "y")
            {
                var root = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
                var configuration = new DoraConfiguration();
                root.GetSection("DoraConfiguration").Bind(configuration);

                var conn = new MySqlConnection(configuration.ConnectionString);
                var directory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sqls");

                if (!Directory.Exists(directory))
                    Directory.CreateDirectory(directory);

                var files = Directory.GetFiles(directory);

                if (files.Length > 0)
                {
                    conn.Open();

                    foreach (var item in files)
                    {
                        try
                        {
                            var sql = File.ReadAllText(item);
                            var cmd = new MySqlCommand(sql, conn);
                            cmd.ExecuteNonQuery();
                            cmd.Dispose();
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"错误：{e.Message}");
                        }

                    }

                    conn.Close();
                }
                else
                    throw new Exception("./sqls 目录下未发现sql文件");
            }
            else
            {
                Console.WriteLine("任意键退出，good bye,.!");
            }

            Console.ReadLine();
        }
    }
}
